package pe.edu.upla.lamerced.security;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.security.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.stereotype.Repository;

import pe.edu.upla.lamerced.DAO.UsuarioDAO;
import pe.edu.upla.lamerced.bean.Users;

@Repository("userLoginService")
public class AutenticacionJdbcDaoImpl extends JdbcDaoImpl{

	private Logger logger = Logger.getLogger(AutenticacionJdbcDaoImpl.class);
		
	@Autowired
	UsuarioDAO usuarioDAO;
	
	@Autowired
	public AutenticacionJdbcDaoImpl(DataSource dataSource){
		setDataSource(dataSource);
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) {
		try {
						
			UserDetails user = super.loadUserByUsername(username);
			logger.debug("usuario login "+user.toString());
			Users usuario = usuarioDAO.obtenerUsuarioPorUsername(username);
			Users ubean = new Users(user.getUsername(), user.getPassword(), user.isEnabled(), user.getAuthorities());
			ubean.setUsername(usuario.getUsername());
			ubean.setPassword(usuario.getPassword());
			ubean.setTipo(usuario.getTipo());
			ubean.setNombre(usuario.getNombre());
			ubean.setApePaterno(usuario.getApePaterno());
			ubean.setApeMaterno(usuario.getApeMaterno());
			ubean.setNroDocumento(usuario.getNroDocumento());
			logger.debug(ubean.toString());
			return ubean;	
		} catch (Exception e) {
			e.printStackTrace();
			throw new UsernameNotFoundException("No hay notaria relacionada a este usuario");
		}
	}

	
}
